<?php
// 1. 连接mysql  选择数据库
@header("Content-Type:text/json;charset=utf-8");
@header("Access-Control-Allow-Origin:*");
$conn = mysqli_connect("b-sjisyki6cozhtk.bch.rds.gz.baidubce.com:3306", "b_sjisyki6cozhtk", "12345678", "b_sjisyki6cozhtk");
if (!$conn) { // 如果连接失败 => 脚本在当前退出
    exit('{"status":false,"message":"数据库链接失败"}');
}
mysqli_query($conn, "set names utf8");
mysqli_query($conn, "set character set utf-8"); // 向数据库存数据

if (!(isset($_POST["user"]) && isset($_POST["g_id"]) && isset($_POST["number"]))) {
    exit('{"status":false,"message":"请传入完整参数"}');
}
$user = $_POST["user"];
$g_id = $_POST["g_id"];
$number = $_POST["number"];




global $conn;
$sql = "select id,number from `idbiao` where user = '$user' and g_id='$g_id'";
$result = mysqli_query($conn, $sql);
$obj = array();
if ($result) { // 有结果对象 => 可能有数据
    // print_r($item === null);
    $all = [];
    while ($item = mysqli_fetch_assoc($result)) {
        array_push($all, $item);
    }
    $obj["status"] = true;
    $obj["message"] = "可以加入购物车";
    $obj["list"] = $all;
} else {
    $obj["status"] = false;
    $obj["message"] = "sql语句有误";
    $obj["sql"] = $sql;
}
$n = $obj['list'][0]['id'];
if ($n) {
    $res = $obj['list'][0]['number'] * 1 + $number * 1;
    $obj = array();
    $sql = "update `idbiao` set number = $res where id=$n";
    $result = mysqli_query($conn, $sql);
    if ($result) { // true => 语句执行成功
        $rows = mysqli_affected_rows($conn);
        if ($rows > 0) {
            $obj["status"] = true;
            $obj["message"] = "加入购物车成功1";
        } else {
            $obj["status"] = false;
            $obj["message"] = "加入购物车失败1";
        }
    } else {
        $obj["status"] = false;
        $obj["message"] = "sql语句有误1";
        $obj["sql"] = $sql;
    }
} else {
    $obj = array();
    $sql = "insert into `idbiao` (g_id,user,number) values('$g_id','$user','$number')";
    $result = mysqli_query($conn, $sql);
    if ($result) { // true => 语句执行成功
        $rows = mysqli_affected_rows($conn);
        if ($rows > 0) {
            $obj["status"] = true;
            $obj["message"] = "加入购物车成功";
        } else {
            $obj["status"] = false;
            $obj["message"] = "加入购物车失败";
        }
    } else {
        $obj["status"] = false;
        $obj["message"] = "sql语句有误";
        $obj["sql"] = $sql;
    }
}
echo json_encode($obj);
